<?php
// +-----------------------+
// | 注释不留名，代码随便用 |
// +-----------------------+

namespace addons\install;

use addons\library\Plugs;
use think\service\AddonsService;
use think\Db;
use think\Exception;

class Install
{

    private static $instance;


    public static function getInstance()
    {
        if (empty(self::$instance)) {
            self::$instance = new static;
        }
        return self::$instance;
    }

    public function execute()
    {
        if (is_file(__DIR__ . '/install.lock')) {
            return;
        }
        try {
            $res = Db::transaction(function () {
                $this->makeSql();
            });

        }catch (\PDOException $exception){
            return ;
        }
        $this->makeConfig();
        $this->installManager();
        $this->insertAssets();
        file_put_contents(__DIR__ . '/install.lock', 1);
    }

    public function makeSql()
    {
        $sql = file_get_contents(__DIR__ . '/install.sql');
        $pdo = Db::connect()->getConnection()->getPdo();
        $pdo->exec($sql);
    }


    /**
     * 生成配置
     */
    public function makeConfig()
    {
        $file = dirname(dirname(__DIR__)) . '/src/config.php';
        copy($file, env('root_path') . 'config/addons.php');

    }

    /**
     * 安装插件管理页面
     */
    public function installManager()
    {
        $name = 'manager';
        $addons = Plugs::factory(2, $name);
        $addons->setLocal(dirname(__DIR__) . DIRECTORY_SEPARATOR);
        $addons->deployAssets();
        $bootstrapClasses = $addons->getBootstrapClass();
        if (class_exists($bootstrapClasses)) {
            (new $bootstrapClasses)->install();
        }
    }

    /**
     * 插入资源链接
     */
    public function insertAssets()
    {
        $resource = env('app_path') . 'admin/view/index/index.html';
        $content = file_get_contents($resource);
        if(!preg_match("@\\\addons\\\\taglib\\\Preload@", $content)){
            $content = str_replace(
                ['</head>', '</body>'],
                ["{taglib name='\\addons\\taglib\\Preload'}{Preload:css /}\n</head>", "{Preload:js /}\n</body>"],
                $content
            );
            file_put_contents($resource, $content);
        }

    }
}